package ssi.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ssi.tools.Connector;

/**
 * Servlet implementation class DeleteAccountServlet
 */
@WebServlet("/DeleteAccountServlet")
public class DeleteAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession(true);
		String hashCode =  request.getParameter("code");
		String mail=request.getParameter("mail");
		try{
			Connection connection = new Connector().getConnection();
    		Statement statement = connection.createStatement();
    		ResultSet result = statement.executeQuery("SELECT id FROM `users` WHERE `password`='"+ hashCode +"'&& email='"+mail+"'");
    		if(result.next()){
    		int id=result.getInt(1);
    		statement.executeUpdate("Delete from users where id="+id);
    		session.setAttribute("user", null);
			session.invalidate();
			response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        	response.setHeader("Location", "/SSIProject/index.jsp?page=deleteAccountSuccess");
        	result.close();
			connection.close();
			
    		}else{
    			response.sendError(404);
    			result.close();
    			connection.close();
    		}
		}catch(Exception e){
			response.sendError(404);
		}
	}
	}


